import html2canvas from "html2canvas";
import jsPDF from "jspdf";
import { Ref } from "vue";
import { HTMLRenderExposed } from "./HTMLRender";

// 定义每个页面的大小和方向
const pageWidth = 210; // A4 页面宽度（毫米）
const pageHeight = 296; // A4 页面高度（毫米）

// 定义 Canvas 的分辨率（与 PDF 分辨率相同）
const dpi = 300;
const canvasWidth = pageWidth * dpi / 25.4;
const canvasHeight = pageHeight * dpi / 25.4;

const createHtml2canvasOptions = () => {
  // 创建一个新的 Canvas，并设置其分辨率
  const canvas = document.createElement('canvas');
  canvas.width = canvasWidth;
  canvas.height = canvasHeight;
  canvas.getContext('2d')?.scale(1.66, 1.66);

  // 设置 html2canvas 配置参数
  return {
    allowTaint: true,
    useCORS: true,
    logging: true,
    scale: 2,
    canvas
  };
}

export const exportPDF = async (elementArray: HTMLDivElement[]) => {
  const pdf = new jsPDF('portrait', "mm", [pageWidth, pageHeight], false);

  const addImage = async (element: HTMLDivElement) => {
    const html2canvasOptions = createHtml2canvasOptions();
    const canvasDom = await html2canvas(element, html2canvasOptions);
    const imgData = canvasDom.toDataURL("image/jpeg", 1);
    pdf.addImage(imgData, "JPEG", 0, 0, pageWidth, pageHeight);
  }

  await elementArray.reduce(async (promise, current, currentIndex) => {
    await promise
    await addImage(elementArray[currentIndex])
    if (currentIndex < elementArray.length - 1) {
      pdf.addPage()
    }
    return Promise.resolve()
  }, Promise.resolve())

  pdf.save('test')
}

// 简历dom的宽度
export const width = 850;

// 宽高比例
const heightScale = 1.41428571;

// 简历dom的高度
export const height = width * heightScale;

// 打印元素的宽度
export const wapperWidth = 749

// 打印元素的高度
export const wapperHeight = wapperWidth * heightScale

// 打印元素 与 简历dom 宽度比例
export const transformScale = wapperWidth / width

// 分割线高度
export const dividerHeight = 5

// 打印元素上下边距
export const verticalpadding = 20

// 简历dom内容高度
export const resumePageHeight = height - ((verticalpadding / transformScale) * 2)

export const getExposeConfig = (doms: HTMLDivElement[]) => {
  return {
    exportPDF: () => {
      if (!doms.length) return
      exportPDF(doms)
    },
    exportMd: () => {

    },
    exportImage: () => {

    },
    generateCover: async (coverName) => {
      if (!doms.length) return
      const html2canvasOptions = createHtml2canvasOptions()
      const canvasDom = await html2canvas(doms[0], html2canvasOptions);
      const blob = await new Promise<Blob | null>(resolve => {
        canvasDom.toBlob(resolve)
      });
      const file = new File([blob!], `${coverName}.png`, { type: 'image/png' });
      return file
    }
  } as HTMLRenderExposed
}